/*
 * @Description: axios封装
 * @Author: Chenx
 * @Date: 2023-03-22 15:00:18
 * @LastEditors: Chenx
 * @LastEditTime: 2023-04-27 16:30:45
 */
import axios, { type AxiosRequestConfig } from 'axios'
import { userStore } from '@/store/modules/user'
import { ElMessage } from 'element-plus'
import { getLocale } from '@/locales' // 获取当前语言的方法
const { NODE_ENV, VUE_APP_BASE_URL, VUE_APP_API } = process.env
const IS_PROD = ['production', 'prod'].includes(NODE_ENV) // 是否为生产环境
const baseURL = IS_PROD ? `${String(VUE_APP_BASE_URL)}${String(VUE_APP_API)}` : VUE_APP_API

const https = () => {
  const user = userStore()
  const config: AxiosRequestConfig = {
    baseURL,
    timeout: 20000,
    headers: {
      language: getLocale(),
      Authorization: user.getToken
    }
  }
  /* 初始化axioas */
  const service = axios.create(config)
  /* 请求拦截器 */
  service.interceptors.request.use(
    (config) => {
      // do something
      console.log('----------baseURL:', baseURL)

      return config
    },
    (error) => {
      // 拦截接口超时
      const isTimeOut = error.code === 'ECONNABORTED' && error.message.indexOf('timeout') !== -1
      if (isTimeOut) {
        ElMessage('接口超时，请稍后重试')
      }
      // // 处理响应失败
      return Promise.reject(error)
    }
  )

  /* 响应拦截器 */
  service.interceptors.response.use(
    (response) => {
      // do something
      console.log('http请求返回值：', response.data)
      return Promise.resolve(response.data)
    },
    (error) => {
      // 拦截接口超时
      const isTimeOut = error.code === 'ECONNABORTED' && error.message.indexOf('timeout') !== -1
      if (isTimeOut) {
        ElMessage('接口超时，请稍后重试')
      }
      // 处理响应失败
      return Promise.reject(error)
    }
  )

  return service
}

export enum Method {
  GET = 'GET',
  POST = 'POST',
  PUT = 'PUT',
  PATCH = 'PATCH',
  DELETE = 'DELETE'
}

export enum ContentType {
  form = 'application/x-www-form-urlencoded',
  json = 'application/json; charset=utf-8',
  multipart = 'multipart/form-data'
}
/**
 * 网络请求参数
 */
// export interface RequestParams {
//   [key: string]: any
// }

export default https
